<!-- 分类树 -->
<template>
  <el-card shadow="never">
    <el-input v-model="deptName" placeholder="材料分类名称" clearable>
      <template #prefix>
        <el-icon>
          <Search />
        </el-icon>
      </template>
    </el-input>

    <el-tree ref="deptTreeRef" class="mt-2" node-key="id" :data="deptList"
      :props="{ children: 'children', label: 'label' }" :expand-on-click-node="false" :filter-node-method="handleFilter"
      default-expand-all highlight-current @node-click="handleNodeClick" />
  </el-card>
</template>

<script setup lang="ts">
import MaterialCategoryAPI from "@/api/business/material/materialCategory.api";

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: undefined,
  },
});

const deptList = ref<OptionType[]>(); // 分类列表
const deptTreeRef = ref(); // 分类树
const deptName = ref(); // 分类名称

const emits = defineEmits(["node-click", "update:modelValue"]);

const deptId = useVModel(props, "modelValue", emits);

watchEffect(
  () => {
    deptTreeRef.value.filter(deptName.value);
  },
  {
    flush: "post", // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/**
 * 分类筛选
 */
function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }
  return data.label.indexOf(value) !== -1;
}

/** 分类树节点 Click */
function handleNodeClick(data: { [key: string]: any }) {
  deptId.value = data.value;
  emits("node-click");
}

onBeforeMount(() => {
  MaterialCategoryAPI.getOptions().then((data) => {
    deptList.value = data || [];
    if (data && data.length) {
      deptTreeRef.value.setCurrentKey(data[0].value);
      handleNodeClick(data[0]);
    }
  });
});

defineExpose({
  deptList,
});
</script>
